package com.xb.loan.encryptor.crypt.impl;


import com.xb.loan.encryptor.cache.RsaKeyCacheManager;
import com.xb.loan.encryptor.crypt.Encryptor;
import com.xb.loan.encryptor.util.RSAUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class UserEncryptor implements Encryptor {
	
	private static Log log = LogFactory.getLog(UserEncryptor.class);

	@Override
	public String encrypt(String id, String key, String msg) {
		
		String keyIndex = getKeyIndex(id, key);
		
		byte[] priKeyData = RsaKeyCacheManager.getUserKeyCache().getPriKey(keyIndex);
		
		if(priKeyData == null){
			
			log.info("UserEncryptor.encrypt not get useIndex " + keyIndex + " private key.");
			return null;
		}
		
		String sign = null;
		
		try {
			
			sign = RSAUtils.sign(msg.getBytes("utf-8"), priKeyData);
			
		} catch (Exception e) {
			
			log.error("UserEncryptor.encrypt have exception,useIndex:" + keyIndex,e);
		}
		
		return sign;
	}

	@Override
	public boolean encryptValidate(String id, String key, String msg,
                                   String encryptResult) {
		
		String keyIndex = getKeyIndex(id, key);
		
		byte[] pubKeyData = RsaKeyCacheManager.getUserKeyCache().getPubKey(keyIndex);
		
		if(pubKeyData == null){
			
			log.info("UserEncryptor.encrypt not get userIndex " + keyIndex + " public key.");
			return false;
		}
		
		boolean verify = false;
		
		try {
			
			verify = RSAUtils.verify(msg.getBytes("utf-8"), pubKeyData, encryptResult);
			
		} catch (Exception e) {
			
			log.error("UserEncryptor.encryptValidate have exception,userid:" + id + ",objId:" + key,e);
		}
		
		return verify;
		
	}

	

	private String getKeyIndex(String userId, String objId) {

		if (userId == null || objId == null) {

			return "default";
		}

		return String.valueOf((Integer.parseInt(userId.substring(userId
				.length() - 2)) + Integer.parseInt(objId.substring(objId
				.length() - 2))) % 100);
	}
	
	public static void main(String[] args) {
		
		UserEncryptor encryptor = new UserEncryptor();
		
		System.out.println(encryptor.encrypt("0210", "100002", "123"));
	}
}
